import {defineStore} from 'pinia';

const store = {
    id: "area",
    state(){
        return {
            areaMap: {},
            areaData: {}
        }
    },

    getters: {

    },

    actions: {
        async getAreaList(parentCode) {
            if(Helper.empty(parentCode)) {
                parentCode = "0";
            }

            if(this.areaData[parentCode]) {
                return this.areaData[parentCode];
            }

            let {code, data} = await Http.get("/common/area", {parentCode});
            if(code == 200) {
                let areaList = [];
                data.forEach(d => {
                    this.areaMap[d.code] = d.name;
                    areaList.push({label: d.name, value: d.code, leaf: d.level == 3});
                })

                this.areaData[parentCode] = areaList;
                return areaList;
            }

            return [];
        },

        find(dataList, code) {
            if(Helper.emptyArray(dataList)) {
                return null;
            }

            for (let i=0;i<dataList.length;i++) {
                let data = dataList[i];
                if(data.value == code) {
                    return data;
                }

                let res = this.find(data.children, code);
                if(res != null) {
                    return res;
                }
            }

            return null;
        }
    },
}

export default defineStore(store)
